package com.heima.test11;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class SendRunnable implements Runnable {
    private int sendport;
    private String sendIp;
    //1 创建socket对象
    DatagramSocket ds;
    Scanner sc = new Scanner(System.in);

    public SendRunnable(DatagramSocket ds, String sendIp, int sendport) {
        this.ds = ds;
        this.sendport = sendport;
        this.sendIp = sendIp;
    }

    @Override
    public void run() {
        while (true) {
            try {
                //2 创建数据包对象
                String s = sc.next(); //发送的数据
                byte[] bytes = s.getBytes();//数据转为字节数组
                InetAddress address = InetAddress.getByName(sendIp);//对方的ip地址
                DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, sendport);
                //3 发送
                ds.send(packet);
            } catch (IOException e) {
                System.out.println(e);
            }
        }
    }
}
